import React from 'react';
import { 
  Upload, 
  Button, 
  Select,
  Typography,
  Alert,
  Spin,
  Space,
  Card,
  message
} from 'antd';
import { 
  LoadingOutlined,
  ScanOutlined,
  CopyOutlined,
  InboxOutlined
} from '@ant-design/icons';
import { pdfService } from '../services/pdfService';
import type { UploadProps } from 'antd';
import styles from './OCRTool.module.css';

const { Dragger } = Upload;
const { Option } = Select;
const { Text } = Typography;

const OCRTool: React.FC = () => {
  const [loading, setLoading] = React.useState(false);
  const [selectedFile, setSelectedFile] = React.useState<File | null>(null);
  const [recognizedText, setRecognizedText] = React.useState<string>('');
  const [lang, setLang] = React.useState<string>('chi_sim+eng');

  const handleFileSelect = (info: any) => {
    const file = info.file;
    if (!file) return;

    const isValidFormat = [
      'application/pdf',
      'image/png',
      'image/jpeg',
      'image/jpg'
    ].includes(file.type);

    if (!isValidFormat) {
      message.error('请上传 PDF 或图片文件(PNG/JPG)');
      return;
    }

    setSelectedFile(file);
    setRecognizedText('');
  };

  const handleOCR = async () => {
    if (!selectedFile) {
      message.warning('请先选择文件');
      return;
    }

    try {
      setLoading(true);
      const response = await pdfService.ocrFile(selectedFile, lang);
      
      if (response.code === 200 && response.data && response.data.text) {
        setRecognizedText(response.data.text);
        message.success('识别完成');
      } else if (response.message === 'success' && response.data) {
        setRecognizedText(response.data);
        message.success('识别完成');
      } else {
        console.error('Invalid response format:', response);
        message.error('识别结果格式错误');
        setRecognizedText('');
      }
    } catch (error) {
      console.error('OCR Error:', error);
      message.error('识别过程出错');
      setRecognizedText('');
    } finally {
      setLoading(false);
    }
  };

  const handleCopyText = () => {
    if (recognizedText) {
      navigator.clipboard.writeText(recognizedText)
        .then(() => message.success('文本已复制到剪贴板'))
        .catch(() => message.error('复制失败'));
    }
  };

  const renderRecognizedText = (text: string) => {
    try {
      if (typeof text !== 'string') {
        return <div>识别结果格式错误</div>;
      }

      return text.split('\n').map((line, index) => (
        <div key={index} style={{ marginBottom: '8px', lineHeight: '1.6' }}>
          {line || <br />}
        </div>
      ));
    } catch (error) {
      return <div>显示结果时出错</div>;
    }
  };

  const uploadProps: UploadProps = {
    name: 'file',
    multiple: false,
    accept: '.pdf,.png,.jpg,.jpeg',
    showUploadList: false,
    beforeUpload: () => false,
    onChange: handleFileSelect,
  };

  return (
    <div className={styles.container}>
      {!selectedFile && !recognizedText && (
        <div className={styles.uploadSection}>
          <Dragger {...uploadProps} className={styles.draggerContainer}>
            <p className="ant-upload-drag-icon">
              <InboxOutlined style={{ fontSize: '48px', color: '#40a9ff' }} />
            </p>
            <p className="ant-upload-text">
              点击或拖拽文件到此区域
            </p>
            <p className="ant-upload-hint">
              支持PDF和图片格式（JPG、PNG等）
            </p>
          </Dragger>
          
          <div className={styles.controlSection}>
            <Select 
              value={lang} 
              onChange={setLang}
              style={{ minWidth: 150 }}
            >
              <Option value="chi_sim+eng">中文+英文</Option>
              <Option value="chi_sim">仅中文</Option>
              <Option value="eng">仅英文</Option>
            </Select>

            <Button
              type="primary"
              icon={loading ? <LoadingOutlined /> : <ScanOutlined />}
              onClick={handleOCR}
              loading={loading}
              disabled={!selectedFile}
            >
              开始识别
            </Button>
          </div>
        </div>
      )}

      {selectedFile && !recognizedText && (
        <Alert
          className={styles.uploadSection}
          message={
            <Space size="middle" align="center" style={{ width: '100%', justifyContent: 'center' }}>
              <Text type="secondary">
                已选择文件: {selectedFile.name}
              </Text>
              <Select 
                value={lang} 
                onChange={setLang}
                style={{ minWidth: 150 }}
              >
                <Option value="chi_sim+eng">中文+英文</Option>
                <Option value="chi_sim">仅中文</Option>
                <Option value="eng">仅英文</Option>
              </Select>
              <Button
                type="primary"
                icon={loading ? <LoadingOutlined /> : <ScanOutlined />}
                onClick={handleOCR}
                loading={loading}
              >
                开始识别
              </Button>
              <Button onClick={() => {
                setSelectedFile(null);
                setRecognizedText('');
              }}>
                重新选择
              </Button>
            </Space>
          }
          type="info"
          showIcon
        />
      )}

      <div className={styles.resultSection}>
        {loading ? (
          <div className={styles.loadingContainer}>
            <Spin size="large" />
            <Text type="secondary">正在识别中...</Text>
          </div>
        ) : recognizedText ? (
          <Card 
            className={styles.resultCard}
            title="识别结果"
            extra={
              <Space>
                <Button 
                  type="link" 
                  icon={<CopyOutlined />}
                  onClick={handleCopyText}
                >
                  复制全部
                </Button>
                <Button 
                  type="link"
                  onClick={() => {
                    setSelectedFile(null);
                    setRecognizedText('');
                  }}
                >
                  重新识别
                </Button>
              </Space>
            }
          >
            <div className={styles.resultContent}>
              {renderRecognizedText(recognizedText)}
            </div>
          </Card>
        ) : null}
      </div>
    </div>
  );
};

export default OCRTool; 